package org.example.chat.client;

import org.example.chat.common.Message;
import org.example.chat.common.MessageType;
import org.example.chat.common.User;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

public class QQClient {
    public static void main(String[] args) throws Exception {
        new QQClient();
    }

    private Socket clientSocket = new Socket(InetAddress.getByName("127.0.0.1"), 8888);
    ManageClientThreadConnectServer manageClientThread = new ManageClientThreadConnectServer();
    User user = new User();

    public QQClient() throws Exception {

        boolean loop = true;

        while (loop) {
            System.out.println("===========欢迎登陆网络通信系统============");
            System.out.println("           1 登陆系统");
            System.out.println("           9 退出系统");
            System.out.println("input your choice? 1 or 9");

            Scanner scanner = new Scanner(System.in);
            String choice = scanner.next();
            if (choice.equals("1")) {
                loginSystem();
            } else if (choice.equals("9")) {
                exitSystem();
                loop = false;
            } else {
                System.out.println("input correct number please guy");
                continue;
            }
        }
    }

    private void loginSystem() throws Exception {
//        while (true){
        System.out.println("welcome login system");
        Scanner scanner = new Scanner(System.in);
        System.out.println("tell me your userId");
        String userId = scanner.next();
        System.out.println("and your password bitch");
        String password = scanner.next();

        //将客户端的消息发送到服务端查证，是否有此人
        System.out.println("wait a moment bitch, l ask server check you now");
        //创建消息包裹，给服务器大哥发过去
        //User user = new User();
        user.setUserId(userId);
        user.setPassword(password);

        //用socket创建通信链路，将打包好的user消息包发出去给服务器
        OutputStream outputStream = clientSocket.getOutputStream();
        //传输的是对象类型的消息，就用对象io流
        ObjectOutputStream oos = new ObjectOutputStream(outputStream);
        oos.writeObject(user);

        System.out.println("服务端已经返回消息啦，开始读取消息");

        //检查用户是否登录的消息包已经发送，等待服务器回应，到底这个逼是不是真实存在的用户
        InputStream inputStream = clientSocket.getInputStream();
        ObjectInputStream ois = new ObjectInputStream(inputStream);
        //知道服务器给回复过来的消息是Message类型，所以就直接转换下
        Message message = (Message) ois.readObject();
        //判断下服务器回复过来的消息，如果服务器大哥回过来消息说这个逼确实是登录成功了，那么就给到这个人尊贵的会员服务，要是没有此人就把他赶出去
        if (message.getMsgType().equalsIgnoreCase(MessageType.LOGIN_SUCCESS.getCode())) {
            System.out.println("congratulation , " + message.getSender() + " login success");
            //客户端登陆成功了，就把对应的用户的账号密码记录
            user.setUserId(userId);
            user.setPassword(password);
            //服务器大哥说此人登录成功了，给予春天般温暖的服务，单独起线程服务，和服务器牵条线，每个线程就代表单独是一个用户
            ClientThreadConnectServer threadConnectServer = new ClientThreadConnectServer(userId,clientSocket);
            new Thread(threadConnectServer).start();
            //登陆成功了，就把客户端及对应的线程记录下
            manageClientThread.addClientThreadConnectServer(userId, threadConnectServer);

            //登录成功啦，进入登录用户界面
            while (true) {
                System.out.println("=============net second menu, welcome 100 enter system==============");
                System.out.println("             1 显示在线用户列表");
                System.out.println("             2 群发消息");
                System.out.println("             3 私聊消息");
                System.out.println("             4 发送文件");
                System.out.println("             9 退出系统");
                System.out.println("bitch, please make a decide again please");

                String choose = scanner.next();
                switch (choose) {
                    case "1":
                        onlineUsers();
                        break;
                    case "2":
                        publicChat();
                        break;
                    case "3":
                        privateChat();
                        break;
                    case "4":
                        sendFile();
                        break;
                    case "9":
                        exitSys();
                        break;
                    default:
                        break;
                }
            }
        } else {
            //登录失败了，那就赶走吧
            System.out.println("登录失败啦");
            clientSocket.close();
        }
    }
//    }

    private void onlineUsers() throws Exception {
        //客户端的登录检查过后，客人就是上帝了，拥有了这条线程的权利
        Message message = new Message();
        message.setMsgType(MessageType.ONLINE_USERS.getCode());
        message.setSender(user.getUserId());
        //客户端将客户的需求再次打包消息传给服务器大哥
        try {
            ClientThreadConnectServer client = manageClientThread.getClientThreadConnectServer(user.getUserId());
            OutputStream outputStream = client.getSocket().getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(outputStream);
            oos.writeObject(message);
        } catch (IOException e) {
            throw new Exception("客户端发送查询在线用户列表出错啦");
        }
    }

    private void publicChat() throws Exception {
        System.out.println("群聊啊，write word for public please");
        Scanner scanner = new Scanner(System.in);
        String content = scanner.next();
        //将话打包成消息发送给客户端
        Message publicMessage = new Message();
        publicMessage.setSender(user.getUserId());
        publicMessage.setContent(content);
        publicMessage.setMsgType(MessageType.PUBLIC_CHAT.getCode());
        //将消息发送给服务器，由服务器充当村长角色，大喇叭通知大家
        //客户端将客户的需求再次打包消息传给服务器大哥
        ClientThreadConnectServer client = manageClientThread.getClientThreadConnectServer(user.getUserId());
        OutputStream outputStream = client.getSocket().getOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(outputStream);
        oos.writeObject(publicMessage);
        System.out.println("客户端选择群聊，发送人： " + user.getUserId() + "发送内容： " + content);
    }

    private void privateChat() throws Exception {
        System.out.println("私聊");
        Scanner scanner = new Scanner(System.in);
        System.out.println("who you want to talk with ?");
        String receiverId = scanner.next();
        System.out.println("what you want to say ?");
        String content = scanner.next();

        //打包消息
        Message priMsg = new Message();
        priMsg.setReceiver(receiverId);
        priMsg.setContent(content);
        priMsg.setSender(user.getUserId());
        priMsg.setMsgType(MessageType.PRIVATE_CHAT.getCode());
        //将消息发送给服务器，由服务器转发消息给指定的用户
        ClientThreadConnectServer clientThread = manageClientThread.getClientThreadConnectServer(user.getUserId());
        ObjectOutputStream oos = new ObjectOutputStream(clientThread.getSocket().getOutputStream());
        oos.writeObject(priMsg);
        System.out.println("客户端向服务器请求和某人发送私聊信息");
    }

    private void sendFile() throws Exception {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入你想给谁发文件");
        String receciveId = scanner.next();
        System.out.println("发送源文件及格式 e:\\a.txt ");
        String srcFile = scanner.next();
        System.out.println("发送文件保存地址及格式 e:\\b.txt ");
        String desFile = scanner.next();

        //io取读文件 "e:\\a.txt"
        File file = new File(srcFile);
        FileInputStream fis = new FileInputStream(file);
        int data = 0;
        byte[] buf = new byte[1024];
        while ((data = fis.read(buf)) != -1){
            System.out.println("读取的数据： "+new String(buf,0,data));
            //将数据复制到指定目录 "e:\\b.txt"
            File cpfile = new File(desFile);
            FileOutputStream fos = new FileOutputStream(cpfile);
            fos.write(buf,0,data);
        }

        //打包消息
        Message fileMsg = new Message();
        fileMsg.setSender(user.getUserId());
        fileMsg.setReceiver(receciveId);
        fileMsg.setSrcFile(srcFile);
        fileMsg.setDestFile(desFile);
        fileMsg.setMsgType(MessageType.SEND_FILE.getCode());
        //sender 发送给服务器，由服务器负责转发下消息，给 receiver
        ClientThreadConnectServer senderThread = manageClientThread.getClientThreadConnectServer(user.getUserId());
        //等待服务器响应
        ObjectOutputStream oos = new ObjectOutputStream(senderThread.getSocket().getOutputStream());
        oos.writeObject(fileMsg);
    }

    private void exitSys() throws Exception {
        Message message = new Message();
        message.setMsgType(MessageType.EXIT_SYSTEM.getCode());
        message.setSender(user.getUserId());
        //客户端将客户的需求再次打包消息传给服务器大哥
        ClientThreadConnectServer client = manageClientThread.getClientThreadConnectServer(user.getUserId());
        OutputStream outputStream = client.getSocket().getOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(outputStream);
        oos.writeObject(message);
        System.out.println("客户端: "+user.getUserId()+" 请求退出系统");
    }

    private void exitSystem() {
        System.out.println("are you sure exit system? y or n");
        Scanner scanner = new Scanner(System.in);
        String yOrN = scanner.next();
        if ("y".equalsIgnoreCase(yOrN)) {
            return;
        }
    }
}
